﻿using Dapper;
using liaowa2.Entity.DTO;
using liaowa2.Entity.InputDTO;
using liaowa2.Entity.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace liaowa2.Dao.Manager
{
    public class ManagerUserDao
    {
        public static bool ChangPwd(string newPwd, string userCode)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                string sql = "update Manager set password=@pwd where user_code=@userCode";
                int result = conn.Execute(sql, new { userCode = userCode, pwd = newPwd }, commandType: CommandType.Text);
                return result > 0 ? true : false;
            }
        }

        public static bool CheckUserName(string userName)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                string sql = "select top 1 * from Manager where user_name=@userName";
                ManagerUser ManagerUser = conn.Query<ManagerUser>(sql, new { userName = userName }, commandType: CommandType.Text).FirstOrDefault();
                return ManagerUser != null ? false : true;
            }
        }

        public static int ManagerChangePwd(string userName, string oldPwd, string newPwd)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                var p = new DynamicParameters();
                p.Add("@UserName", userName);
                p.Add("@Password", oldPwd);

                var ManagerUser = conn.Query<ManagerUser>(" select top 1 * from Manager where user_name = @UserName and  password=@Password and Enable=0", p, commandType: CommandType.Text).FirstOrDefault();
                if (ManagerUser == null)
                {
                    return 1;
                }
                conn.Execute(" update Manager set password=@Password where Id=@userId",
                    new { Password = newPwd, userId = ManagerUser.id }, commandType: CommandType.Text);
                return 0;
            }
        }

        public static ResultMsg ManagerLogin(string UserName, string Password)
        {
            var p = new DynamicParameters();
            p.Add("@UserName", UserName);
            p.Add("@Password", Password);

            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                ManagerUser ManagerUser = new ManagerUser();
                ManagerUser = conn.Query<ManagerUser>(" select top 1 * from Manager where user_name = @UserName and  password=@Password and IsEnable=0", p, commandType: CommandType.Text).FirstOrDefault();

                ResultMsg result = new ResultMsg();
                if (ManagerUser == null)
                {
                    result.State = false;
                    result.Single = null;
                    result.Message = "登陆失败，用户名或者密码错误！";
                    return result;
                }
                result.State = true;
                result.Single = ManagerUser;
                return result;
            }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public static List<ManagerUser> GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * ");
            strSql.Append(" FROM Manager ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }

            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                var model = conn.Query<ManagerUser>(strSql.ToString(), null, commandType: CommandType.Text).ToList();
                return model;
            }
        }

        /// <summary>
        /// 用户分页管理
        /// </summary>
        /// <param name="input"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static EntityPage<ManagerUser> GetManagerUserPage(ManagerUserView input)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("  Manager mu join ManagerRole r on mu.role_ID=r.ID ");
            strSql.Append("  where mu.role_ID>=@roleId ");

            if (!string.IsNullOrEmpty(input.Phone))
            {
                strSql.Append(" and charindex(@phone,m.telephone)>0");
            }

            DepperSqlHelp<ManagerUser> help = new DepperSqlHelp<ManagerUser>();
            EntityPage<ManagerUser> result = help.Pagination<ManagerUser>(strSql.ToString(), input.CurrentIndex, input.PageSize, true,
                "mu.*,r.role_name RoleName,r.role_type,r.is_sys", "mu.id", new
                {
                    roleId = input.RoleId,
                    phone = input.Phone
                });


            return result;
        }


        public static bool IsEnable(int id, int enable)
        {
            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                var result = conn.Execute(" update Manager set IsEnable=@IsEnable where Id = @Id", new { id = id, IsEnable = enable }, commandType: CommandType.Text);
                return result > 0 ? true : false;
            }
        }

        public static async Task<ManagerUser> GetModel(int id = 0)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append(" select top 1 * from Manager where id=@id");

            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                return await conn.QueryFirstOrDefaultAsync<ManagerUser>(strSql.ToString(), new
                {
                    id = id
                });
            }
        }


        public static bool AddUser(ManagerUser input)
        {

            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append(" INSERT INTO [dbo].[Manager] (role_id,user_name,user_code, ");
                strSql.Append(" password,real_name,telephone,email,add_time,");
                strSql.Append(" headimg,IsEnable) values(@role_id,@user_name,@user_code,");
                strSql.Append(" @password,@real_name,@telephone,@email,@add_time,");
                strSql.Append(" @headimg,@IsEnable) ");

                var paramete = new DynamicParameters();
                paramete.Add("@role_id", input.role_id);
                paramete.Add("@user_name", input.user_name);
                paramete.Add("@user_code", input.user_code);
                paramete.Add("@password", input.password);
                paramete.Add("@real_name", input.real_name);
                paramete.Add("@telephone", input.telephone);
                paramete.Add("@email", input.email);
                paramete.Add("@add_time", DateTime.Now);
                paramete.Add("@headimg", input.headimg);
                paramete.Add("@IsEnable", 0);

                return conn.Execute(strSql.ToString(),paramete)>0?true:false;

            }

        }


        public static bool EditUser(ManagerUser input)
        {

            using (IDbConnection conn = SqlConn.OpenConnectionStar())
            {

                StringBuilder strSql = new StringBuilder();
                strSql.Append(" update Manager set role_id=@role_id, ");
                strSql.Append(" user_name=@user_name,");
                strSql.Append(" password=@password,");
                strSql.Append(" real_name=@real_name,");
                strSql.Append(" telephone=@telephone,");
                strSql.Append(" email=@email,");
                strSql.Append(" add_time=@add_time,");
                strSql.Append(" headimg=@headimg,");
                strSql.Append(" IsEnable=1 ");
                strSql.Append(" where id=@id ");

                return conn.Execute(strSql.ToString(), new
                {
                    id = input.id,
                    role_id = input.role_id,
                    user_name=input.user_name,
                    password=input.password,
                    real_name=input.real_name,
                    telephone=input.telephone,
                    email=input.email,
                    add_time=DateTime.Now,
                    headimg=input.headimg
                }) > 0 ? true : false;

            }
        }

    }
}
